package cn.wegoteam.shop.action;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import cn.wegoteam.shop.action.BaseAction;
import cn.wegoteam.shop.inter.CartServiceInter;
import cn.wegoteam.shop.inter.OrderServiceInter;
import cn.wegoteam.shop.inter.PayImpServiceInter;
import cn.wegoteam.shop.inter.PayServiceInter;
import cn.wegoteam.shop.inter.ProductServiceInter;
import cn.wegoteam.shop.po.Cart;
import cn.wegoteam.shop.po.Order;
import cn.wegoteam.shop.service.AlipayService;
import cn.wegoteam.shop.util.Const;
import cn.wegoteam.shop.util.PostAndGetRequset;

@ParentPackage("default")
@Namespace("/")
@Controller
public class CartAction extends BaseAction<Cart> {
	@Autowired
	private ProductServiceInter productService; 
	@Autowired
	private OrderServiceInter orderService; 
	@Autowired
	private CartServiceInter cartService;
	@Action(value = "productComment", results = { @Result(name = "success", location = PRODUCT
			+ "comment.jsp") })
	public String productComment(){
		map.put("product.id", getParameter("p_id", "-1"));
		map.put("flag", 2);
		paramMap.put("p_id", getParameter("p_id", "-1"));
		List<Cart> coms = cartService.getList(pageBean, map,"id desc");
		request.setAttribute("cms", coms);
		return SUCCESS;
	}
	/****
	 * 需要添加拦截器
	 * @return
	 */
	@Action(value = "preComment", results = { @Result(name = "success", location = PRODUCT
			+ "addComment.jsp") })
	public String preComment(){
		Order order = orderService.get(model.getId());
		request.setAttribute("order", order);
		return SUCCESS;
	}
	@Action(value = "comment", results = { @Result(name = "success", location = PRODUCT
			+ "addComment.jsp") })
	public String comment(){
		Cart newCart = cartService.get(model);
		newCart.setComment(model.getComment());
		newCart.setScore(model.getScore());
		//2表示已经评论
		newCart.setFlag(2);
		newCart.setAnonymous(model.isAnonymous()?true:false);
		cartService.update(newCart);
		
		//更新商品评论数
		map.put("id", newCart.getProduct().getId());
		productService.executeByHql("UPDATE Product SET commentNum = commentNum+1 WHERE id=:id", map);
		
		//返回评论后的Cart
		Order order = new Order();
		Set<Cart> cs = new HashSet<Cart>();
		cs.add(newCart);
		order.setCarts(cs);
		request.setAttribute("order", order);
		
		//查询是否还有未评论的商品，没有则更新order
		map.clear();
		map.put("order.id", newCart.getOrder().getId());
		map.put("flag", 1);
		if(cartService.getCount(map)==0){
			order = newCart.getOrder();
			order.setState(Const.STATIC_COMMENT);
			orderService.update(order);
		}
		return SUCCESS;
	}
}
